package com.siblings.loan.ui.user.act

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.base.utils.log.LogHelper
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.loan.R
import com.siblings.loan.databinding.ActFeedbackBinding
import com.siblings.loan.http.ApiService
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.user.adapter.SibFeedbackImageAdapter
import com.siblings.loan.ui.user.impl.SibUserFeedbackPresenterImpl
import com.siblings.loan.ui.user.view.ISibUserFeedbackView
import com.siblings.loan.utils.dialog.KefuDialog
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.imagecovert.ImageConvert
import com.siblings.mvp.MvpAct
import org.json.JSONObject
import java.io.File


/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/18 13:45
 * @Annotation：意见反馈
 */
class SibFeedbackAct: MvpAct<ISibUserFeedbackView, SibUserFeedbackPresenterImpl>(), ISibUserFeedbackView {

    lateinit var binding: ActFeedbackBinding
    //图片列表
    private var imgAdapter: SibFeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun getSibRootView(): View {
        binding = ActFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createMvpPresenter(): SibUserFeedbackPresenterImpl {
        return SibUserFeedbackPresenterImpl(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initSibView() {
        setSibTitleBarVisibility(View.VISIBLE)
        setSibTextTitle(getString(R.string.feedback_title))
        setSibTextTitleGravity(Gravity.CENTER)
        setSibBackBtnRes(R.mipmap.pic_back_theme)
        setSibRightBtnRes(R.mipmap.pic_kefu_theme)

        initSibRecyclerView()
        binding.editType.setHint(String.format(getString(R.string.feedback_edit_hint),100))
        binding.textTypeLength.text = "0/100"
        binding.editRemark.setHint(String.format(getString(R.string.feedback_edit_hint),1000))
        binding.textRemarkLength.text = "0/1000"

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                LogHelper.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    LogHelper.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        //最多只能选三张
                        if (imgAdapter!!.itemCount == 3){
                            imgAdapter!!.removeItem(0)
                        }
                        val imgObj = JSONObject()
                        imgObj.put("isDefault",false)
                        imgObj.put("imgPath",localPath)
                        imgAdapter!!.addLastItem(imgObj)

                        mvpPresenter.uploadSibImageAction(localPath)
                    }
                }

            } else {
                LogHelper.e("No media selected")
            }
        }
    }

    override fun initSibListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showSibKefuDialog("UserFeedback Page")
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CUSTOMER,"UserFeedback Page")
        }
        //输入框监听
        binding.editType.addTextChangedListener(IFeedbackTypeChangeListener)
        binding.editType.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editType.text.toString().isNotEmpty()){
                HttpHelper.addSibEventAction(SibEventType.FORM.SIB_FORM_USER_FEEDBACK_DESCRIBE,binding.editType.text.toString())
            }
        }

        //输入框监听
        binding.editRemark.addTextChangedListener(IRemarkChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                HttpHelper.addSibEventAction(SibEventType.FORM.SIB_FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }

        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            val typeText = binding.editType.text.toString()
            if (typeText.isEmpty()){
                showSibToast(getString(R.string.feedback_type_title))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showSibToast(getString(R.string.feedback_remark_title))
                return@setOnClickListener
            }
            showSibLoading()
            val params = JSONObject().addCommonParams().apply {
                put("path", ApiService.API_PATH.SIB_API_FEEDBACK_SUBMIT_PATH)
                put("type",typeText)//反馈类型
                put("opinion",remark)//反馈内容
            }
            mvpPresenter.submitSibFeedbackAction(params)
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_FEEDBACK_SUBMIT,"")
        }
    }

    override fun initSibData() {
        mvpPresenter.loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        imgAdapter!!.addFirstItem(imgObj)
    }

    /**
     * 初始化图片列表
     */
    private fun initSibRecyclerView() {
        binding.recyclerView.setHasFixedSize(false)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.recyclerView.layoutManager = layoutManager
        imgAdapter = SibFeedbackImageAdapter(binding.recyclerView)
        binding.recyclerView.adapter = imgAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        imgAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { parent, childView, position ->
            val item = imgAdapter!!.getItem(position)
            when(childView.id){
                R.id.ivDelete -> {//删除
                    if (!item.optBoolean("isDefault")){
                        imgAdapter!!.removeItem(position)

                        //是否需要添加默认图片
                        var isAddDefault = true
                        for (i in 0..<imgAdapter!!.itemCount){
                            if (imgAdapter!!.getItem(i).optBoolean("isDefault")){
                                isAddDefault = false
                                break
                            }
                        }
                        if (isAddDefault){
                            val imgObj = JSONObject()
                            imgObj.put("isDefault",true)
                            imgAdapter!!.addFirstItem(imgObj)
                        }
                    }
                }
                R.id.ivImage -> {//选择图片
                    if (item.optBoolean("isDefault")){
                        hasRequestPermissions()
                    }
                }
            }
        })
    }

    private val IFeedbackTypeChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s!!.length
            binding.textTypeLength.text = "$textLength/100"
        }
    }

    private val IRemarkChangeListener = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            val textLength = s!!.length
            binding.textRemarkLength.text = "$textLength/1000"
        }
    }

    /**
     * 设置意见反馈问题类型列表
     */
    override fun setSibQuestionTypeList(typeList: ArrayList<JSONObject>) {

    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun showSibUploadImageSuccess(imgUrl: String) {
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
        if (destinationDirectory != null && destinationDirectory!!.isFile){
            destinationDirectory!!.delete()
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun showSibSubmitSuccess() {
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },1000)
    }


    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 显示客服dialog
     */
    private fun showSibKefuDialog(eventRemark: String){
        val kefuDialog = KefuDialog(this,eventRemark,object : KefuDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        kefuDialog.setCancelable(true)
        kefuDialog.setCanceledOnTouchOutside(true)
        kefuDialog.show()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_USER_FEEDBACK_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addSibEventAction(SibEventType.PAGE.SIB_PAGE_USER_FEEDBACK_END,"")
    }
}